/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.asn1.ui.builder;

import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.xtext.builder.BuilderParticipant;
import org.eclipse.xtext.generator.IFileSystemAccess;
import org.eclipse.xtext.generator.OutputConfiguration;

import com.google.inject.Inject;

import de.thwildau.tm.moses.asn1.ui.Activator;
import de.thwildau.tm.moses.asn1.ui.preferences.PreferenceConstants;
import de.thwildau.tm.moses.common.builder.IBuildContextVisitor;
import de.thwildau.tm.moses.common.builder.ISyntaxCheckerService;
 

/**
 * A Builder that does the following build steps
 * <ol>
 * <li>Checks the ASN.1 Syntax (if enabled)</li>
 * <li>Runs super.build-Method (i.e. Code Generation)</li>
 * <li>Organized the Imports of the generated code (if enabled)</li>
 * </ol>
 *
 * @author Thomas Kistel
 * @version $Revision: 767 $
 *
 */
public class Asn1BuilderParticipant extends BuilderParticipant {

    @Inject
    private IBuildContextVisitor contextVisistor;
    
    @Inject
    private OrganizeImportsBuildPart organizeImports;

    /* (non-Javadoc)
     * @see BuilderParticipant#build(IXtextBuilderParticipant.IBuildContext, IProgressMonitor)
     */
    @Override
    public void build(IBuildContext context, IProgressMonitor monitor) throws CoreException {
        List<IFile> affectedFiles = contextVisistor.getAffectedFiles(context, "asn", "asn.1", "asn1");
        if(affectedFiles.size() == 0) {
//            System.out.println("No ASN.1 files affeccted.");
            return;
        } 
        if(affectedFiles.size() > 1) {
            Activator.logWarning("More than one ASN.1 file (totally " + affectedFiles.size() + ") were affected. Taking the first one.");
        }
       
        IFile source = affectedFiles.get(0);
        IStatus result = checkSyntax(source, context, monitor);
        if(result.isOK()) {
            
            // check whether the general Compiler setting is activated
            if(isEnabled(context)) {
                // run the build-part of the Xtext-BuilderParticipant which may also generates Code
                super.build(context, monitor);
                
                // Checks if we also should do an OrganizeImport
                if(doOrganizeImports()) {
                    OutputConfiguration outputConfig = getOutputConfigurations(context).get(IFileSystemAccess.DEFAULT_OUTPUT);
                    if(outputConfig != null) {
                        IFolder srcFolder = context.getBuiltProject().getFolder(outputConfig.getOutputDirectory());
                        organizeImports.build(srcFolder);
                    }
                }
            }
        } else {
            // log the acutal result, which was not ok
            Activator.getInstance().getLog().log(result);
        }
    }
    
    /**
     * Checks the syntax of the given <code>source</code>. If no {@link ISyntaxCheckerService} was
     * bound to this bundle this method does nothing and returns an OK-Status.
     */
    private IStatus checkSyntax(IFile source, IBuildContext context, IProgressMonitor monitor) throws CoreException {
        ISyntaxCheckerService service = Activator.getInstance().getSyntaxCheckerService();
        if(service != null) {
            return service.perform(source, context, monitor);
        }
        return Status.OK_STATUS;
    }
    
    private boolean doOrganizeImports() {
        IPreferenceStore prefs = Activator.getInstance().getPreferenceStore();
        return prefs.getBoolean(PreferenceConstants.ORGANIZE_IMPORTS_AFTER_CODEGEN);
    }
}
